package com.uziot.bucket.common.util.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 功能描述: <br>
 * AES加密工具类，实现对字符串的加密和解密操作
 *
 * @author shidt
 * @date 2019-12-31 22:51
 */
@Slf4j
public class AESUtil {

    private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private static final String ENCODING = "utf-8";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String IV_STRING = "A-16-Byte-String";
    private static final String KEY_ALGORITHM = "AES";

    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param password 加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password) {
        try {
            byte[] byteContent = content.getBytes(ENCODING);
            byte[] pwdBytes = password.getBytes(ENCODING);
            SecretKeySpec secretKey = new SecretKeySpec(pwdBytes, KEY_ALGORITHM);
            byte[] initParam = IV_STRING.getBytes(ENCODING);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            byte[] result = cipher.doFinal(byteContent);

            return Base64Utils.encodeToString(result);
        } catch (Exception e) {
            throw new RuntimeException("AES加密失败！");
        }
    }

    /**
     * 解密处理
     *
     * @param content  解密内容
     * @param password 私钥
     * @return 解密内容
     */
    public static String decrypt(String content, String password) {

        try {
            byte[] byteContent = Base64Utils.decodeFromString(content);
            byte[] pwdBytes = password.getBytes(ENCODING);
            SecretKeySpec secretKey = new SecretKeySpec(pwdBytes, KEY_ALGORITHM);
            byte[] initParam = IV_STRING.getBytes(ENCODING);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
            byte[] result = cipher.doFinal(byteContent);

            return new String(result, ENCODING);
        } catch (Exception e) {
            throw new RuntimeException("AES解密失败");
        }

    }

}